<?php
// +----------------------------------------------------------------------
// | [KyPHP System] Copyright (c) 2020 http://www.kuryun.com/
// +----------------------------------------------------------------------
// | [KyPHP] 并不是自由软件,你可免费使用,未经许可不能去掉KyPHP相关版权
// +----------------------------------------------------------------------
// | Author: fudaoji <fdj@kuryun.cn>
// +----------------------------------------------------------------------
/**
 * Created by PhpStorm.
 * Script Name: Msg.php
 * Create: 2020/6/10 17:23
 * Description: 粉丝消息
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace app\mp\controller;

use app\admin\controller\FormBuilder;
use app\mp\controller\handler\mp\MessageObj;

class Msg extends Base
{
    /**
     * @var  \think\Model
     */
    private $msgM;
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->msgM = model('mpMsg');
    }

    /**
     * 聊天详情
     * @return mixed
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function detail(){
        if($this->mpInfo['verify_type_info'] < 0 && $this->mpInfo['service_type_info'] != 2){
            $this->error('当前公众号未获取发送客服消息接口');
        }
        $openid = input('openid', '');
        $follow = model('mpFollow')->getOneByMap(['openid' => $openid, 'mpid' => $this->mpId]);
        if(request()->isPost()){
            $post_data = input('post.');
            if(!empty($post_data['media_type']) && !empty($post_data['media_id'])){
                $media_type = $post_data['media_type'];
                $media = model('media_' . $media_type)->getOne(['id' => $post_data['media_id'], 'uid' => $this->adminId]);
                $message = MessageObj::$media_type($media);
                $last_msg = $this->msgM->getList([0, 1], ['mpid' => $this->mpId, 'openid' => $openid, 'is_reply' => 0], ['id' => 'desc'], true, 1)[0];
                if($last_msg['create_time'] - time() > (48 * 3600 - 60)){
                    $this->error('与粉丝已经超过48小时没有互动了，无法主动发送消息');
                }
                if($this->mpApp->customer_service->message($message)->to($openid)->send()){ //客服发送消息
                    //入库
                    $media_array = $message->toXmlArray();
                    if($media_type == 'text'){
                        $content = $media_array;
                    }else{
                        $content = $media_array[ucfirst($media_type)];
                        $content['url'] = $media['url'];
                    }
                    $this->msgM->addOne([
                        'pid' => $last_msg['id'],
                        'openid' => $openid,
                        'mpid' => $this->mpInfo['id'],
                        'type' => $media_type,
                        'is_reply' => 1,
                        'content' => json_encode($content, JSON_UNESCAPED_UNICODE),
                        'nickname' => $this->mpInfo['nick_name'],
                        'headimgurl' => $this->mpInfo['head_img']
                    ]);
                    $this->msgM->updateOne([
                        'id' => $last_msg['id'],
                        'mpid' => $this->mpInfo['id'],
                        'status' => 1
                    ]);
                    $this->success('回复成功', url('detail', ['openid' => $openid]));
                }else{
                    $this->error('回复失败，请刷新重试', '', ['token' => request()->token()]);
                }
            }
        }

        $where = ['mpid' => $this->mpId];
        $types = model('mpRule')->types();
        $follow_ids = $this->msgM->getField('id', ['openid' => $openid]);
        $where['id|pid'] = ['in', $follow_ids];
        $data_list = $this->msgM->getList([0, 20], $where, ['id' => 'desc'], true, 1);
        foreach ($data_list as $k  => $value){
            $value['content'] = json_decode($value['content'], true);
            $data_list[$k] = $value;
        }
        $assign = [
            'data_list' => $data_list,
            'types' => $types
        ];
        $builder = new FormBuilder();
        $builder->setTemplate('msg/detail')
            ->addFormItem('title', 'legend', '与'.$follow['nickname'].'的聊天', '')
            ->addFormItem('media', 'choose_media', '回复类型', '回复类型', ['types' => model('mpRule')->types()], 'required');
        return $builder->show($assign);
    }

    /**
     * 消息列表
     * @return mixed
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function index(){
        $where = ['mpid' => $this->mpId, 'is_reply' => 0];
        $search_key = input('search_key', '');
        $search_key && $where['content'] = ['like', '%'.$search_key.'%'];
        $types = model('mpRule')->types();

        $data_list = $this->msgM->page($this->pageSize, $where, ['id' => 'desc'], true, 1);
        foreach ($data_list as $k  => $value){
            $value['content'] = json_decode($value['content'], true);
            $data_list[$k] = $value;
        }
        $page = $data_list->appends(['search_key' => $search_key])->render();
        $assign = [
            'data_list' => $data_list,
            'page' => $page,
            'search_key' => $search_key,
            'types' => $types
        ];
        return $this->show($assign);
    }


    /**
     * 获取临时素材链接
     * @author: fudaoji<fdj@kuryun.cn>
     */
    public function getTempMediaUrlPost(){
        if(request()->isPost()){
            $media_id = input('media_id', '');
            $id = input('id', '');
            $msg = $this->msgM->getOne(['id' => $id, 'mpid' => $this->mpId], 1);
            $content = json_decode($msg['content'], true);
            if(!empty($content['url'])){
                $this->success('从数据库获取的', '', ['url' => $content['url']]);
            }
            $stream = $this->mpApp->media->get($media_id);
            if($stream instanceof \EasyWeChat\Kernel\Http\StreamResponse){
                $filename = $stream->save(UPLOAD_PATH . 'temp/');
                $url = '/public/uploads/temp/' . $filename;
                if(config('system.upload.driver') == 'qiniu'){
                    if($res = fetch_to_qiniu(request()->domain() . $url)){
                        $url = $res;
                        @unlink(UPLOAD_PATH . 'temp/' . $filename);
                    }
                }
                //修改数据url
                $content['url'] = $url;
                $this->msgM->updateOne([
                    'id' => $id, 'mpid' => $this->mpId,
                    'content' => json_encode($content, JSON_UNESCAPED_SLASHES)
                ]);
                $this->success('success', '', ['url' => $url]);
            }
            $this->error('获取素材链接失败');
        }
    }
}